/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.examples;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
import org.apache.hc.core5.http.nio.CapacityChannel;
import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.util.Timeout;

import lombok.extern.slf4j.Slf4j;

import static org.examples.DebugConstants.host;
import static org.examples.DebugConstants.nttsPath;
import static org.examples.DebugConstants.schema;

/**
 * Example of asynchronous HTTP/1.1 request execution with response streaming.
 */
@Slf4j
public class NttsClient {

  private static String buildRequestJsonString(String input, String voice) {
    String s = String.format(
        "{\"audio\": {\"format\": \"opus_ogg\"}, \"text\": {\"contentType\": \"text/plain\", \"content\": \"%s\"}, \"voice\": {\"voiceId\": \"%s\"}}",
        input,
        voice);
    //    log.info("json body={}", s);
    System.out.println(String.format(s));
    return s;
  }

  public static void main(final String[] args) throws Exception {
//    CloseableHttpAsyncClient client = HttpAsyncClients.custom()
//        .set()
//        .build();
    final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    final HttpHost target = new HttpHost(host);
    //    final HttpHost target = new HttpHost("httpbin.org");
    String text = "The result will be millions of Americans who have insurance who did not have it before.";
    String voice = "zoe";
    String json = buildRequestJsonString(text, voice);
    //    SimpleBody simpleBody=new SimpleBody(null,json,ContentType.APPLICATION_JSON);
    final SimpleHttpRequest request = SimpleRequestBuilder
        //            .get()
        .post()
        .setHttpHost(target)
        .setScheme(schema())
        //        .setPath("/v1/synthesize")
        //        .setPath("/get")
        .setPath(nttsPath())
        //        .setBody(json,ContentType.APPLICATION_JSON)
        .build();
    System.out.println("Executing request " + request);
    BasicAsyncEntityProducer basicAsyncEntityProducer = new BasicAsyncEntityProducer(
        json,
        ContentType.APPLICATION_JSON
    );
    long startTimeMs = System.currentTimeMillis();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    final Future<Void> future = client.execute(
        new BasicRequestProducer(request, basicAsyncEntityProducer),
        new AsyncResponseConsumer() {
          boolean isFirstAudio = true;

          long firstTimeMs;

          int audioBytes = 0;

          @Override
          public void releaseResources() {
            latch.countDown();

          }

          @Override
          public void updateCapacity(CapacityChannel capacityChannel) throws IOException {
            //            capacityChannel.update(999999999);
          }

          @Override
          public void consume(ByteBuffer byteBuffer) throws IOException {
            if (isFirstAudio) {
              firstTimeMs = System.currentTimeMillis();
              long firstAudioLatencyMs = firstTimeMs - startTimeMs;
              System.out.println(String.format("firstAudioLatencyMs=%d", firstAudioLatencyMs));

            }
            isFirstAudio = false;
//            byteBuffer.flip();
            System.out.println(String.format("byteBuffer.position=%d", byteBuffer.position()));
//            byteBuffer.flip();
            audioBytes += byteBuffer.remaining();
            System.out.println(String.format("byteBuffer.remaining=%d", byteBuffer.remaining()));
//                        byteBuffer.flip();
          }

          @Override
          public void streamEnd(List<? extends Header> list) throws HttpException, IOException {
            System.out.println(String.format("streamEnd audioBytes = %d", audioBytes));
          }

          @Override
          public void consumeResponse(HttpResponse httpResponse, EntityDetails entityDetails, HttpContext httpContext,
              FutureCallback futureCallback) throws HttpException, IOException {

          }

          @Override
          public void informationResponse(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
            System.out.println(String.format("informationResponse %ss", httpResponse.getReasonPhrase()));

          }

          @Override
          public void failed(Exception e) {
            System.out.println(String.format("failed %ss", e.getMessage()));

          }
        },
        null
    );
    //    AudioPerfResult audioPerfResult = future.get();
//        future.get();
    try {
      latch.await(20, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
  }

}
